<?php

class LoanController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action admroller here */
        $this->list_sess_unset('controller_loan');
        $this->session_search_key = 'controller_loan';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'loan', '');
    }

    public function viewAction() {
        if ($this->_getParam('ln_id') && $this->_getParam('ln_id') != "") {
            $ln_id = $this->_getParam('ln_id');
        } else {
            $this->_helper->redirector('list', 'loan', '');
        }
        $loanModel = new Model_Loan();
        $loanalldata = $loanModel->fetchEntryByViewId($ln_id);
        $installmentData = $loanModel->getInstallmentData($ln_id);
        $this->view->loanalldata = $loanalldata;
        $this->view->installmentData = $installmentData;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $searchtext = "";
        $searchtext_fromdate = "";
        $searchtext_todate = "";
        $orderField = 'ln_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = "";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'] = "";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'] = "";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'] = "";
        }
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;
        //PAGING_PER_PAGE
        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = ' Please select atleast one checkbox! ';
                }
            }
            /* Search Facility Over Here */
            /*if ($postedData["searchtype_startdate"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['startdate'] = "";
            }
            if ($postedData["searchtype_enddate"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['enddate'] = "";
            }*/
            
            if($postedData["searchtype"]==''){
                $errorMessage[] = "Please select option.";
            }
            if($postedData["searchtype"]){
                $searchtype = $postedData["searchtype"];
                
                
                /*Loan NAME*/
                if($searchtype=='ln_name'){
                    $searchtext = $postedData["searchtext_loan"];
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                /*agent Name*/
                if($searchtype=='ag_name'){
                    $searchtext = $postedData["searchtext_agent"];
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                /*Customer Name*/
                if($searchtype=='cus_name'){
                    $searchtext = $postedData["searchtext_customer"];
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                /*end Date */
                if($searchtype=='ln_enddate'){
                    $searchtext_fromdate = $postedData["searchtext_endfromdate"];
                    $searchtext_todate = $postedData["searchtext_endtodate"];
                    if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ln_enddate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }
                 /*Start Date */
                if($searchtype=='ln_startdate'){
                    $searchtext_fromdate = $postedData["searchtext_startfromdate"];
                    $searchtext_todate = $postedData["searchtext_starttodate"];
                    if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ln_startdate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }
                
              
               
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype']=$searchtype;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext']=$searchtext;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate']=$searchtext_fromdate;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate']=$searchtext_todate;

                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
                $this->view->searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
                $this->view->searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
                $this->view->searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];
            }
            
        } else {
            /*if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = '';
            }*/
             $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
             $searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
             $searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
             $searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];
                /*Loan NAME*/
                if($searchtype=='ln_name'){
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                /*Customer Name*/
                if($searchtype=='cus_name'){
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                /*agent Name*/
                if($searchtype=='ag_name'){
                    if($searchtext!=''){
                        $where = $searchtype ." like '%".$searchtext."%'";
                    }else{
                        $errorMessage[] = "Please enter search text.";
                    }
                }
                
                 /*Start Date */
                if($searchtype=='ln_startdate'){
                    if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ln_startdate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }
                
                 /*end Date */
                if($searchtype=='ln_enddate'){
                    if($searchtext_fromdate!='' && $searchtext_todate!=''){
                       $where = "ln_enddate BETWEEN  '" . $searchtext_fromdate . "' AND '" . $searchtext_todate . "'";
                    
                    }else{
                        $errorMessage[] = "Please select date.";
                    }
                }
                
              
            
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype']=$searchtype;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext']=$searchtext;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate']=$searchtext_fromdate;
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate']=$searchtext_todate;

                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
                $this->view->searchtext = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext'];
                $this->view->searchtext_fromdate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_fromdate'];
                $this->view->searchtext_todate = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtext_todate'];
       }

        $loanModel = new Model_Loan();
        $loansData = $loanModel->fetchLoan($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($loanModel->getLoanCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'loan', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->loansData = $loansData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $loanModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Loan Model 
        $loanModel = new Model_Loan();
        if ($this->_getParam('ln_id') && $this->_getParam('ln_id') != "") {
            $ln_id = $this->_getParam('ln_id');
            $loanModel->deleteLoan($ln_id);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'loan', '');
        } else {
            $loanModel->deleteLoan($ids);
            $this->addSuccessMessage('Record Successfully Deleted');
            $this->_helper->redirector('list', 'loan', '');
        }
    }

    public function formAction() {
        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $loanData = Array();
        $this->view->mode = "Add";

        //Load Loan Model
        $loanModel = new Model_Loan();
         
        
         //Load Loan Model
        $documentModel = new Model_Document();

        
        //Load Loan Form
        $loanForm = new Form_LoanForm();

        
        //Load the agent array for the select box in form 
        $agentArray = $loanModel->getagentArray();
        $loanForm->ln_ag_id->addMultiOptions($agentArray);
        
        //Load the customer array for the select box in form 
        $customerArray = $loanModel->getcustomerArray();
        $loanForm->ln_cus_id->addMultiOptions($customerArray);
        
        
        //Load the status array for the select box in form 
        $statusArray = $loanModel->getStatusArray();
        $loanForm->ln_status->addMultiOptions($statusArray);

        //Check for the loan Parameter
        $loanData['ln_id'] = $this->_request->getParam('ln_id');
        $ln_id = (!empty($loanData['ln_id'])) ? $loanData['ln_id'] : null;

        if (!empty($ln_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $loanModel->fetchEntryById($ln_id);
            $docData['doc_name'] = $data['doc_name'];
            $docData['doc_id'] = $data['doc_id'];
            $this->view->docname = $docData['doc_name'];
        }
        //Populate form 
        $this->view->form = $loanForm->populate($data);
        if ($this->getRequest()->isPost()) {
             if ($this->view->mode == "Add") {
                    //Image Validation
                  /*  if ($_FILES['ln_document']['name'] == '') {
                        $errorMessageArray[] = 'Please upload the document';
                    }*/
                }
               /* if ($_FILES['ln_document']['name'] != '') {
                    $gtlObj = new GTL_Common();
                    $allowedzipFormats = $gtlObj->allowedzipFormats();
                    $responseText = $gtlObj->image_validate($allowedzipFormats, 'ln_document');
                    if ($responseText == 'IMPROPER_FORMAT') {
                        $errorMessageArray[] = 'Please upload the only zip folder'; #'Please upload image with valid file format.';
                    }
                }*/
                
                
            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$loanForm->isValid($postedData)) {
                $errorMessage = $loanForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {
                     
                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                           
                            $folder = $this->config->UPLOAD_PATH . "loan_document/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $docData['doc_name'] = $fileName;
                        }
                    }
                    
                    
                    if ($this->view->mode == "Add") {
                        $loanData['ln_createddate'] = date("Y-m-d H:i:s");
                    }
                    
                   
                    
                    //Loan save
                    $loanData['ln_id'] = $ln_id;
                    $loanData['ln_cus_id'] = $postedData['ln_cus_id'];
                    $loanData['ln_ag_id'] = $postedData['ln_ag_id'];
                    $loanData['ln_name'] = $postedData['ln_name'];
                    $loanData['ln_amount'] = $postedData['ln_amount'];
                    $loanData['ln_advance'] = $postedData['ln_advance'];
                    $loanData['ln_startdate'] = $postedData['ln_startdate'];
                    $loanData['ln_enddate'] = $postedData['ln_enddate'];
                    $loanData['ln_guarantor_name'] = $postedData['ln_guarantor_name'];
                    $loanData['ln_guarantor_address'] = $postedData['ln_guarantor_address'];
                    $loanData['ln_guarantor_mobile'] = $postedData['ln_guarantor_mobile'];
                    $loanData['ln_note'] = $postedData['ln_note'];
                    $loanData['ln_status'] = $postedData['ln_status'];
                    $loanData['ln_updateddate'] = date("Y-m-d H:i:s");
                    $loan_last_id=$loanModel->save($loanData, 'ln_id');
                    
                    if ($this->view->mode == "Add") {
                        $docData['doc_ln_id'] = $loan_last_id;
                    }else{
                        $docData['doc_ln_id'] = $ln_id;
                    }
                    $docData['doc_cus_id'] = $postedData['ln_cus_id'];
                    $docData['doc_status'] = $postedData['ln_status'];
                    $documentModel->save($docData, 'doc_id');
                    
                    if ($this->view->mode == "Add") {
                        $successmessage = 'Loan add successfully';
                    } else {
                        $successmessage = 'Loan updated successfully';
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'loan', '');
                }
            }
        }
        $this->view->loanid = $ln_id;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $loanForm;
    }
    
    //fetch old document of customer using ajax
    public function customerdocumentlistAction(){
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $ln_cus_id = $postedData['ln_cus_id'];
            $documentModel = new Model_Document();
            $documentwhere = "ln_cus_id = ".$ln_cus_id;
            $documentArray = $documentModel->fetchDocument($documentwhere);
            
        }
        exit;
    }
    public function downloadAction(){
        //load model
        $loanModel = new Model_Loan();
        $loan_id = $this->_getParam('ln_id');
       //  $data = $loanModel->fetchEntryById($loan_id);
       // $docData['ln_cus_id'] = $data['ln_cus_id'];
        
        //Load Document Model
        $documentModel = new Model_Document();
        $where_document = "doc_ln_id = ".$loan_id;
        $document_data = $documentModel->fetchDocument($where_document);
        $document_name = $document_data[0]['doc_name'];
        
        $file = $this->config->UPLOAD_PATH . "loan_document/".$document_name;
        $gtlObj = new GTL_Common();
        $download_file = $gtlObj->dl_file($file);
                    
        
        //$this->_helper->redirector('list', 'loan', '');
    } 
    
     public function getcsvAction()
    {   
        
       
        $output = fopen('php://output', 'w');

        if ($this->_getParam('ln_id') && $this->_getParam('ln_id') != "") {
            $ln_id = $this->_getParam('ln_id');
        } else {
            $this->_helper->redirector('list', 'loan', '');
        }
        $loanModel = new Model_Loan();
        $loanalldata = $loanModel->fetchEntryByViewId($ln_id);
        $installmentData = $loanModel->getInstallmentData($ln_id);
        
        
        fputcsv($output, array('Loan Detail'));   
        fputcsv($output, array('Loan Name:',$loanalldata['ln_name']));   
        fputcsv($output, array('Loan Amount:','Rs.'.$loanalldata['ln_amount']));
        fputcsv($output, array('Advanced Amount:','Rs.'.$loanalldata['ln_advance']));
        fputcsv($output, array('Start Date:',$loanalldata['ln_startdate']));
        fputcsv($output, array('End Date:',$loanalldata['ln_enddate']));
        fputcsv($output, array('Guarantor Name:',$loanalldata['ln_guarantor_name']));
        fputcsv($output, array('Customer Name:',$loanalldata['cus_name']));
        fputcsv($output, array('Account Number:',$loanalldata['cus_actnumber']));
        fputcsv($output, array(''));
        fputcsv($output, array(''));
        
        fputcsv($output, array('Installment Detail'));  
        
        fputcsv($output, array('Installment Amount','Credit Date','Uptil Date','Note'));
        
        $row  = array();
        foreach ($installmentData as $key => $value) {
            //$row['loan_name'] = $value['ln_name'];
           // $row['cus_name'] = $value['cus_name'];
            //$row['cus_actnumber'] = $value['cus_actnumber'];
            $row['ins_amount'] = 'Rs.'.$value['ins_amount'];
            $row['ins_creditdate'] = $value['ins_creditdate'];
            $row['ins_uptodate'] = $value['ins_uptodate'];
            $row['ins_note'] = $value['ins_note'];
            /*if($value['ins_status'] == 1){
               $row['status'] = 'Active' ;
            }else{
               $row['status'] = 'Inactive'; 
            }*/
            
            fputcsv($output, $row);   
        }
        $ln_name = str_replace(" ","-", $loanalldata['ln_name']);
        $filename =$ln_name."_".rand();
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename='.$filename.'.csv');
       exit;

    }


}

?>
